package com.fsnmt.maizhuanbao;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.fsnmt.maizhuanbao.bean.Device;
import com.fsnmt.maizhuanbao.printfUtils.PrintfManager;
import com.fsnmt.maizhuanbao.printfUtils.SharedPreferencesManager;
import com.fsnmt.maizhuanbao.qrcodeUtils.ZXingUtil;
import com.fsnmt.maizhuanbao.utils.CacheManager;
import com.fsnmt.maizhuanbao.utils.DeviceUtils;
import com.fsnmt.maizhuanbao.utils.LogUtils;
import com.fsnmt.maizhuanbao.utils.PicturePickUtils;
import com.fsnmt.maizhuanbao.utils.PictureTool;
import com.fsnmt.maizhuanbao.utils.SystemUtils;
import com.fsnmt.maizhuanbao.utils.ToastUtils;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

import java.io.File;
import java.io.IOException;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

public class UnityPlayerNativeActivity extends UnityPlayerActivity {

	private PicturePickUtils picturePickUtils;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		if(SystemUtils.checkStoragePermission(this)){
			CacheManager.init(this);
			picturePickUtils = new PicturePickUtils();
		}else{
			SystemUtils.getStoragePermission(this);
		}
	}


	/****相册***********************************/
	public void _SaveImageToAlbum(String imagePath){
		boolean temp = false;
		File file = new File(imagePath);
        if (file.exists()) {
        	String[] pathdir = imagePath.split("/");
        	String fileName = pathdir[pathdir.length-1];
        	String dirName = pathdir[pathdir.length-2];
    		Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        	try {
				temp= PictureTool.saveFile(bitmap, fileName,dirName);
			} catch (IOException e) {
				e.printStackTrace();
			}
        	PictureTool.insertImage(UnityPlayerNativeActivity.this, fileName,dirName);
        	if (temp) {
        		file.delete();
        		UnityPlayerNativeActivity.this.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						Toast.makeText(UnityPlayerNativeActivity.this, "图片已成功保存至相册", Toast.LENGTH_SHORT).show();
					}
				});	
    		}
    		else {
    			UnityPlayerNativeActivity.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(UnityPlayerNativeActivity.this, "图片保存失败，请重试", Toast.LENGTH_SHORT).show();
					}
				});	
    		}
         }
        else {
        	UnityPlayerNativeActivity.this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(UnityPlayerNativeActivity.this, "图片保存失败，请重试", Toast.LENGTH_SHORT).show();
			}
		});
        }
	}
	

	/**网页接口*******************************************/
	public void _OpenURL(String url){
		if (!DeviceUtils.isNetworkAvailable(UnityPlayerNativeActivity.this)) {
			Toast.makeText(this, "网络异常，请检查网络重试", Toast.LENGTH_SHORT).show();
		}
		else {
			if (null!=url && url.length()>0) {
				if (!url.substring(0, 7).equals("http://")) {
					url="http://"+url;
				}
				Intent intent = new Intent();
		        intent.setAction("android.intent.action.VIEW");
		        Uri content_url = Uri.parse(url);
		        intent.setData(content_url);
		        startActivity(intent);
			}
			else {
				Toast.makeText(this, "网址为空", Toast.LENGTH_SHORT).show();
			}
		}
	}


	String phone;
	/**电话接口**************************/
	public void _OpenPhone(String number){
		if(!TextUtils.isEmpty(number)){
			phone = number;
			SystemUtils.callPhone(number, this);
		}else{
			ToastUtils.show(this,"电话为空");
		}
	}

	/**短信接口**************************/
	public void _OpenMessage(String phoneNumber,String message){
		if(!TextUtils.isEmpty(phoneNumber)){
			Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+phoneNumber));
			intent.putExtra("sms_body", message);
			startActivity(intent);
		}
	}

	/**系统相册接口**************************/
	public void _OpenPhotoAlbum(){
		if(SystemUtils.checkStoragePermission(this)){
			if(null==picturePickUtils) {
				CacheManager.init(this);
				picturePickUtils = new PicturePickUtils();
			}
			picturePickUtils = new PicturePickUtils();
			picturePickUtils.selectPicFromLocal(this,null);
		}else{
			SystemUtils.getStoragePermission(this);
		}
	}



	/**蓝牙打印接口**************************/
	PrintfManager printfManager;
	private AbstractList<BluetoothDevice> bluetoothDeviceArrayList;
	private boolean isRegister = false;
	private final int ImageWidth = 380;
	private final int QRCodeWidth = 340;
	private BluetoothAdapter mBluetoothAdapter = null;
	private static int REQUEST_ENABLE_BT = 2;

	public void _InitPrintf(){
		LogUtils.show("initPrintf()");
		isRegister = false;
		bluetoothDeviceArrayList = new ArrayList<>();
		printfManager = PrintfManager.getInstance(this);
		printfManager.setConnectSuccess(new PrintfManager.ConnectSuccess() {
			@Override
			public void success() {
				LogUtils.show("connectSuccess");
				String bluetoothName = SharedPreferencesManager.getBluetoothName(UnityPlayerNativeActivity.this);
				String bluetoothAddress = SharedPreferencesManager.getBluetoothAddress(UnityPlayerNativeActivity.this);
				ToastUtils.show(UnityPlayerNativeActivity.this,"蓝牙连接成功："+bluetoothName);
				UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "setPrintfConnectStatus", "1");
				UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "setCurrentConnectPrintfDevice", bluetoothName+","+bluetoothAddress);
			}
		});
		printfManager.setConnectFailure(new PrintfManager.ConnectFailure() {
			@Override
			public void failure() {
				UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "setPrintfConnectStatus", "0");
			}
		});
		printfManager.defaultConnection();
	}


	public void _IsOpenBluetooth(){
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if(null!=mBluetoothAdapter && mBluetoothAdapter.isEnabled()) {//蓝牙已经开启
			LogUtils.show("setBluetoothStatus 1 蓝牙已开");
			UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "setBluetoothStatus", "1");
		}else{//蓝牙没有开
			LogUtils.show("setBluetoothStatus 0 蓝牙没开");
			UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "setBluetoothStatus", "0");
		}
	}

	public void _StartPrintf(String url,String content,String cont){
		LogUtils.show("startPrintf()");
		if(printfManager.isCONNECTING()){
			UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "setPrintfConnectStatus", "2");
			ToastUtils.show(this,"蓝牙正在连接，请稍候。");
			return;
		}
		if(TextUtils.isEmpty(url) || TextUtils.isEmpty(content) || TextUtils.isEmpty(cont)){
			ToastUtils.show(this,"打印内容为空");
			return;
		}else{
			ToastUtils.show(this,""+url+","+content+","+cont);
		}
		isRegister = false;
		if(printfManager.isConnect()){
			LogUtils.show("printfBitmap()");
			printfBitmap( url, content);
		}else{
			LogUtils.show("setPrintfConnectStatus 0 未连接打印机");
			UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "setPrintfConnectStatus", "0");
			_IsOpenBluetooth();
		}
	}

	private void printfBitmap(String url, String content) {
		Bitmap bitmap = Bitmap.createBitmap(ImageWidth, ImageWidth, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		canvas.drawColor(Color.WHITE);

		Bitmap bitmap1 = ZXingUtil.encodeQRCode(url, QRCodeWidth, QRCodeWidth);
		canvas.drawBitmap(bitmap1, (ImageWidth-QRCodeWidth)/2, 0, new Paint());

		Paint paint = new Paint();
		paint.setColor(Color.BLACK);
//		paint.setTextSize(DeviceUtils.dip2px(this, 16));
		paint.setTextSize(32);
		paint.setAntiAlias(true);
		float fontWidth = paint.measureText(content);
//		canvas.drawText(content, (ImageWidth - fontWidth) / 2, QRCodeWidth+((ImageWidth-QRCodeWidth)*2/5), paint);
		canvas.drawText(content, (ImageWidth - fontWidth) / 2, ImageWidth-38, paint);

		try {
			Matrix m = new Matrix();
			m.setRotate(180, (float) ImageWidth / 2, (float) ImageWidth / 2);
			Bitmap bm1 = Bitmap.createBitmap(bitmap, 0, 0, ImageWidth, ImageWidth, m, true);
			printfManager.printf(48,50,bm1,this);
		} catch (OutOfMemoryError ex) {
			printfManager.printf(48,50,bitmap,this);
		}
	}


	public void _OpenBuletoothSetting(){
		LogUtils.show("openBluetoothSetting()");
		Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
	}


	public void _StartSearchPrintfDevice(){
		if(Build.VERSION.SDK_INT < 24){
			startSearch();
		}else {
			if (SystemUtils.checkLocationPermission(this)) {
				startSearch();
			} else {
				ToastUtils.show(this, "请求定位权限");
				SystemUtils.getLocationPermission(this);
			}
		}
	}

	private void startSearch(){
		LogUtils.show("startSearchPrintfDevice()");
		bluetoothDeviceArrayList.clear();
		ToastUtils.show(this, "正在搜索");
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mReceiver, filter);
		isRegister = true;
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		} else {
			mBluetoothAdapter.startDiscovery();
			UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "setBluetoothStatus", "2");
		}
	}



	public void _StopSearchBlueTooth(){
		if (mReceiver != null && isRegister) {
			try {
				LogUtils.show("stopSearchPrintfDevice()");
				UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "setBluetoothStatus", "3");
				unregisterReceiver(mReceiver);
				isRegister = false;
				ToastUtils.show(this, "搜索完成");
			}catch (Exception e){
			}
		}
	}



	public void _ConnectPrintfDevice(String name, final String address){
		LogUtils.show("connectPrintfDevice()");
		//先停止搜索
		_StopSearchBlueTooth();
		ToastUtils.show(this, "正在连接...");
		UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "setPrintfConnectStatus", "2");
		//进行配对
		Executors.newCachedThreadPool().execute(new Runnable() {
			@Override
			public void run() {
				try {
					BluetoothDevice mDevice = mBluetoothAdapter.getRemoteDevice(address);
					printfManager.openPrinter(mDevice);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public void _DisConnectPrintfDevice(){
		if(null!=printfManager && printfManager.isConnect()) {
			LogUtils.show("disConnect PrintfDevice()");
			printfManager.disConnect("");
		}
	}

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			//找到设备
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (judge(device,bluetoothDeviceArrayList))
					return;
				bluetoothDeviceArrayList.add(device);
				String s = new Device(device.getName(), device.getAddress()).toString();
				LogUtils.show("find device "+s);
				UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "setNewBluetoothDevice", s);
			}
			//搜索完成
			else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				_StopSearchBlueTooth();
			}
		}
	};

	private boolean judge(BluetoothDevice device, List<BluetoothDevice> devices) {
		if (device == null || devices.contains(device)) {
			return true;
		}
		int majorDeviceClass = device.getBluetoothClass().getMajorDeviceClass();
		if(majorDeviceClass != 1536){
			return true;
		}
		return false;
	}

	/*************************************/


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			if(requestCode == PicturePickUtils.REQUEST_CODE_LOCAL){
//				File file = picturePickUtils.getPictureFile(this, null, requestCode, data);
				if(null!=data && null!=data.getData()) {
					picturePickUtils.cropImageUriWithURi(this, null, data.getData(), 0, 0, 300, 300);
				}else{
					ToastUtils.show(this,"获取相册图片失败");
				}
			}else if(requestCode == PicturePickUtils.REQUEST_CODE_CUT_PICTURE){
				File file = picturePickUtils.getPictureFile(this, null, requestCode, data);
				if(null!=file && file.exists()) {
					String url = file.getAbsolutePath();
					ToastUtils.show(this,url);
					UnityPlayer.UnitySendMessage("(Singleton) AddressManager", "SetPhotoAlbum", url);
				}else{
					ToastUtils.show(this,"裁剪图片失败");
				}
			}
		}
	}




	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		switch (requestCode) {
			case SystemUtils.RequestCode.REQUEST_CODE_ASK_CALL_PHONE:
				if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					SystemUtils.call(phone, UnityPlayerNativeActivity.this);
				} else {
					ToastUtils.show(UnityPlayerNativeActivity.this, "请允许该权限");
				}
				break;
			case SystemUtils.RequestCode.REQUEST_CODE_STORAGE:
				if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					CacheManager.init(this);
					picturePickUtils = new PicturePickUtils();
				} else {
					ToastUtils.show(UnityPlayerNativeActivity.this, "请允许该权限");
				}
				break;
			case SystemUtils.RequestCode.REQUEST_CODE_LOCATION:
				if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					startSearch();
				} else {
					ToastUtils.show(UnityPlayerNativeActivity.this, "请允许该权限");
				}
			default:
				super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		}
	}
}
